//
//  SRClassMemberListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/7/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRClassMemberListViewController.h"

#import "SRSchoolClassServices.h"
#import "SRClassMemberListTableViewCell.h"
#import "UIButton+FZGreenButton.h"
//#import <MJRefresh/MJRefresh.h>

@interface SRClassMemberListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *items;
@property (assign, nonatomic) NSInteger pageIndex;
@property (strong, nonatomic) UIButton *rightButton;
@property (strong, nonatomic) UIButton *deleteButton;

@end

@implementation SRClassMemberListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
	self.title = @"班级成员";
	
    [self setupData];
    [self setupView];
    [self setupNavigationItem];
    
    if (self.userType == SRSchoolClassUserTypeTeacher) {
        self.rightButton.hidden = NO;
    } else {
        self.rightButton.hidden = YES;
    }
    
    [self showLoadingViewWithCompletedBlock:nil];
    [self queryData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

#pragma mark - setup

- (void)setupData {
    self.pageIndex = 0;
    self.items = [@[] mutableCopy];
}

- (void)setupView {
    
    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 100;
    self.tableView.allowsMultipleSelection = YES;
    
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRClassMemberListTableViewCell bundle:nil] forCellReuseIdentifier:kSRClassMemberListTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorColor = [UIColor whiteColor];
   
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    
//    [self.tableView addLegendHeaderWithRefreshingBlock:^{
//        weakSelf.pageIndex = 0;
//        [weakSelf queryData];
//    }];
//    
//    [self.tableView addLegendFooterWithRefreshingBlock:^{
//        [weakSelf queryData];
//    }];
    
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.deleteButton setTitle:@"移除班级" forState:UIControlStateNormal];
   
    
    [self.deleteButton applyGreenBackgroundColorNoCorner];
    [self.deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.deleteButton setTitleColor:[FZStyleSheet currentStyleSheet].color_7 forState:UIControlStateDisabled];
    
    [self.deleteButton addTarget:self action:@selector(onDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
    self.deleteButton.hidden = YES;
    
    [self.view addSubview:self.deleteButton];
    
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(0);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.equalTo(self.view);
        make.bottom.equalTo(self.deleteButton.mas_top);
    }];
}

- (void)setupNavigationItem {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 60, 40);
    [rightButton setTitle:@"管理" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH4;
    
    self.rightButton = rightButton;
    [rightButton addTarget:self action:@selector(onRightButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [self setRightBarButtonItem:rightItem];
}

#pragma mark - Query Data


- (void)queryData{
    self.pageIndex = 0;
    WEAKSELF
    [SRSchoolClassServices queryClassMemberListPage:self.pageIndex groupID:self.classModel.identifiter successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf hideLoadingView];
//        [weakSelf.tableView.footer endRefreshing];

        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {

            NSArray *addItems = @[];
            if ([responseDataObject isKindOfClass:[NSArray class]]) {
                addItems = responseDataObject;
            }

            if (weakSelf.pageIndex == 0) {
                [weakSelf.items removeAllObjects];
            }

            if ([addItems count] <= 0) {
                    //没有更多
//                [weakSelf.tableView.footer noticeNoMoreData];
                if (weakSelf.pageIndex == 0) {
                    [weakSelf emptyLoadingViewWithTitle:nil];
                }

            } else {
                weakSelf.pageIndex += [addItems count];
                [weakSelf.items addObjectsFromArray:addItems];
            }
			weakSelf.title = [NSString stringWithFormat:@"班级成员（%d）", [weakSelf.items count] ];

            [weakSelf.tableView reloadData];

        } else {
            if (weakSelf.pageIndex == 0) {
                [weakSelf failedLoadingViewWithTitle:nil];
            }
        }

    } failureBlock:^(id responseObject, NSError *error) {
//        [weakSelf.tableView.footer endRefreshing];

        if ([weakSelf.items count] <= 0) {
            [weakSelf failedLoadingViewWithTitle:nil];
        }

    }];
    
}

#pragma mark - Event


- (void)updateDeleteButtonTitle {
    NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
    NSInteger count=indexPaths.count;
    if(count==0){
        [self.deleteButton setTitle:@"移除班级" forState:UIControlStateNormal];
        [self.deleteButton setEnabled:NO];
    }else if (count>0){
        [self.deleteButton setTitle:[NSString stringWithFormat:@"移除班级(%ld)",(long)count] forState:UIControlStateNormal];
        [self.deleteButton setEnabled:YES];
    }
}

- (void)onRightButton:(id)sender {
    BOOL isEditing = !self.tableView.editing;
    if (!self.tableView.editing) {
        [self.tableView setEditing:YES animated:YES];
        [self.rightButton setTitle:@"取消" forState:UIControlStateNormal];
    }else{
        [self.tableView setEditing:NO animated:YES];
        [self.rightButton setTitle:@"管理" forState:UIControlStateNormal];
    }
    [self updateDeleteButtonTitle];
    
    [self setViewIsEditing:isEditing];
}
    //多选删除
-(void)onDeleteButton:(UIButton*)button {
    
    NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
    if (indexPaths.count == 0) {
        
        [self onRightButton:self.rightButton];
        return;
    }
    
    NSMutableArray *uids = [[NSMutableArray alloc] init];
    for (NSInteger i = indexPaths.count - 1; i >= 0; i --) {
        NSIndexPath *indexPath = [indexPaths objectAtIndex:i];

        SRClassMemberItemModel* memberModel = [self.items objectAtIndex:indexPath.row];
        
        [uids addObject:[NSString stringWithFormat:@"%@", memberModel.uid]];
    }
    
    [self onRightButton:self.rightButton];
    [self deleteUsersWithUIDS:uids count:indexPaths.count];
}

- (void)deleteUsersWithUIDS:(NSArray *)uids count:(NSInteger)counts {
    [self.deleteButton setEnabled:NO];
    NSString *uidString = [uids componentsJoinedByString:@","];
    
    [self startProgressHUD];
//    NSMutableDictionary *parameters = [@{} mutableCopy];
//    [parameters setValue:@(1) forKey:@"type"];
//    [parameters setValue:self.classModel.identifiter forKey:@"group_id"];
//    [parameters setValue:uidString forKey:@"del_uid"];
//        //    [self askClassMemberData];
//        //    return;
    
    WEAKSELF
    [SRSchoolClassServices deleteClassMemberGroupID:self.classModel.identifiter delUIDs:uidString successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"删除成功"];
            
            [weakSelf queryData];
            
            [self.deleteButton setTitle:@"移除班级" forState:UIControlStateNormal];
        
            if (self.DeleteStudentSuccessBlock) {
                self.DeleteStudentSuccessBlock(uids);
            }
            
        }else if (statusCode == kFZRequestStatusCodeError){
            if (!message || [message length] <= 0) {
                [weakSelf showHUDErrorMessage:@"删除失败"];
            } else {
                [weakSelf showHUDErrorMessage:message];
            }
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.deleteButton setEnabled:YES];
        });
        
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDError];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.deleteButton setEnabled:YES];
        });
    }];
}


- (void)setViewIsEditing:(BOOL)isEditing {
    [self.tableView setEditing:isEditing animated:YES];
        //    [button setTitle:@"取消" forState:UIControlStateNormal];
    self.deleteButton.hidden= !isEditing;
    
    
    if (isEditing) {
        [self.deleteButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(50);
        }];
    } else {
        [self.deleteButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.items count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRClassMemberListTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRClassMemberListTableViewCell forIndexPath:indexPath];

    SRClassMemberItemModel *item = self.items[indexPath.row];
    [cell updateCellInfo:item];

    return cell;
}


#pragma mark - UITableViewDelegate

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleInsert | UITableViewCellEditingStyleDelete;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    SRClassMemberItemModel *item = self.items[indexPath.row];
    if ([item.uid longLongValue] == [[SRLoginUser userID] longLongValue]) {
            //管理员列表，若是管理员进入不能删除
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.editing){
        [self updateDeleteButtonTitle];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.tableView.editing){
        
//        NSString* sectionName = [self.sectionArray objectAtIndex:indexPath.section];
//        if ([sectionName isEqualToString:kSectionIndexManger]) {
//                //管理员列表，若是管理员进入不能删除
//            if (self.userLevel == 2) {
//                [tableView deselectRowAtIndexPath:indexPath animated:YES];
//                return ;
//            }
//        }
        [self updateDeleteButtonTitle];
    }else{
            //
    }
}



@end
